<template>
  <div class="login-container">
    <div class="nav">
      <van-icon name="home-o" @click="toIndex" />
      <van-nav-bar title="网易严选" />
      <van-icon name="search" />
    </div>

    <!-- logo -->
    <div class="logo">
      <img style="width: 200px" src="//yanxuan.nosdn.127.net/static-union/164793255107785e.png" alt="" />
    </div>

    <!-- 登录 -->
    <van-form @submit="onConfirm">
      <van-cell-group inset>
        <van-field
          v-model="username"
          name="username"
          label="用户名"
          placeholder="用户名"
          :rules="[{ required: true, message: '请填写用户名' }]"
        />
        <van-field
          v-model="password"
          type="password"
          name="password"
          label="密码"
          placeholder="密码"
          :rules="[{ required: true, message: '请填写密码' }]"
        />
      </van-cell-group>
      <div style="margin: 16px">
        <van-button block type="danger" native-type="submit"> 登录 </van-button>
      </div>
    </van-form>

    <!--  -->
  </div>
</template>

<script lang="ts" setup>
import { reqLogin } from '@/api/login'
import router from '@/router'
import { showSuccessToast, showFailToast } from 'vant'
import { ref } from 'vue'
import useUserStore from '@/store/userInfo'
import 'vant/es/toast/style'

// 仓库实例化
const userStore = useUserStore()

// 用户名和密码
const username = ref('')
const password = ref('')

// 点击home回首页
const toIndex = () => {
  router.push('/')
}

// 点击登录
const onConfirm = async (data: any) => {
  // 整理参数
  const { password, username } = data
  try {
    // 调用登录接口
    const res = await reqLogin(username, password)
    console.log(res)

    if (res) {
      //  登录成功之后提示用户
      showSuccessToast('登录成功')

      // 存token\userInfo到本地
      localStorage.setItem('token', res.data.token)
      localStorage.setItem('userInfo', JSON.stringify(res.data))

      // 存到仓库
      userStore.addToken(res.data.token)
      userStore.addUserInfo(res.data)

      // 跳转登录页
      router.push('/')
    }
  } catch (error) {
    showFailToast('账号或密码不正确,请重新登录！')
  }
}
</script>

<script lang="ts">
export default {
  name: 'VLogin'
}
</script>

<style lang="scss" scoped>
.logo {
  width: 100%;
  // width: 400px;
  display: flex;
  justify-content: center;
  margin-top: 70px;
}
.nav {
  display: flex;
  justify-content: space-between;
  .van-icon {
    padding: 15px;
  }
  .van-nav-bar {
    width: 200px;
  }
}
</style>
